package com.guardchina.framework.mybatis.impl;

import com.guardchina.framework.mybatis.api.RoutingDataSourceStrategy;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 描述：轮询获取从库数据源
 *
 * @author lwb
 * @date 2019/3/22 9:57
 */
public class PollingDataSourceStrategy implements RoutingDataSourceStrategy {

    private AtomicInteger count = new AtomicInteger(0);
    @Override
    public String deterMineSlaveDataSource(String[] slaveDataSourceKeys) {

        //防止count超过最大的integer变成负数，此处需要使用绝对值
        int num = Math.abs(count.addAndGet(1)) % slaveDataSourceKeys.length;
        return slaveDataSourceKeys[num];
    }
}
